package com.codedancer.campus.manager.runner;

import cn.hutool.json.JSONUtil;
import com.codedancer.campus.common.constant.DataCacheKey;
import com.codedancer.campus.common.utils.RedisUtil;
import com.codedancer.campus.mapper.RoleMapper;
import com.codedancer.campus.po.Role;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * 角色编码自动缓存
 */
@Component
@Slf4j
@Order(1)
public class RoleEncodeDataCacheAutoRunner implements ApplicationRunner {

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Resource(name = "dataCacheRedisTemplate")
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 自动缓存角色编码
     *
     * @param args
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("项目启动，开始缓存角色编码数据");
        // 先从redis中删除缓存的角色编码数据
        redisUtil.setRedisTemplate(stringRedisTemplate);
        redisUtil.delete(DataCacheKey.ROLE_ENCODE_DATA_KEY);
        // 查询全部角色
        List<Role> roles = roleMapper.selectList(null);
        List<String> roleEncodes = roles.stream().map(Role::getEncode).collect(Collectors.toList());
        redisUtil.setStringValue(DataCacheKey.ROLE_ENCODE_DATA_KEY, JSONUtil.toJsonStr(roleEncodes));
        log.info("角色编码数据成功缓存到Redis");
    }
}
